package com.example.mykotilin.navigation2

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.example.mykotilin.R
import com.example.mykotilin.databinding.DonutItemBinding
import com.example.mykotilin.databinding.FragmentDonutListBinding


class DonutListFragment : Fragment() {
    private lateinit var donutListViewModel: DonutListViewModel  //对应的viewModel
    // 新建adapter实例
    private val adapter = DonutListAdapter(onEdit = { donut ->   //回调的编辑页面
        findNavController().navigate(  //导航到页面，这里需要携带参数
            DonutListFragmentDirections.actionDonutListToDonutEntry(donut.id)
        )
    },
        onDelete = {  //删除回调同时进行通知
            NotificationManagerCompat.from(requireContext()).cancel(it.id.toInt())
            donutListViewModel.delete(it)
        })


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //View的填充
        return FragmentDonutListBinding.inflate(inflater, container, false).root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val binding = FragmentDonutListBinding.bind(view)  //view的绑定
        val donutDao = DonutDatabase.getDatabase(requireContext()).donutDao() //获取数据dao类
        donutListViewModel = ViewModelProvider( //生成viewModel实例
            this,
            DonutViewModelFactory(donutDao)
        ).get(DonutListViewModel::class.java)

        //建立监听器
        donutListViewModel.donuts.observe(viewLifecycleOwner) { donuts ->
            Log.i("---->>", "更新了哈哈")
            donuts.forEach {
                Log.i("---->>", it.description)
            }
            //进行数据更新
            adapter.submitList(donuts)
        }
        //进行赋值
        binding.recyclerView.adapter = adapter
        //FloatingActionButton监听
        binding.fab.setOnClickListener { fabView ->
            fabView.findNavController().navigate( //进行页面跳转
                DonutListFragmentDirections.actionDonutListToDonutEntry()
            )
        }

    }


}